<?php

/* * *** including classes and setting constants **** */
require_once 'classes/DatabaseConnection.class.php';
require_once 'classes/Inventory.class.php';
require_once 'classes/SideBar.class.php';
require_once 'classes/Div_Container.class.php';
require_once 'classes/My_Form.class.php';
require_once 'classes/My_HTML_Page.class.php';
require_once 'classes/Page_Main_Content.class.php';
require_once 'classes/Page_Header.class.php';
require_once 'classes/Cal_Day_Container.class.php';
require_once 'classes/ResourceType.class.php';
require_once 'classes/User.class.php';
require_once 'classes/Slot.class.php';
require_once 'classes/Resource.class.php';
require_once 'classes/Reservation.class.php';

// MODELS
require_once 'models/ReservationDB.class.php';
require_once 'models/ResourceTypeDB.class.php';
require_once 'models/ResourceDB.class.php';
require_once 'models/UserDB.class.php';
require_once 'models/SlotDB.class.php';
// VIEWS
require_once 'views/Home_View.class.php';
require_once 'views/Reports_View.class.php';
require_once 'views/Calendar_View.class.php';
require_once 'views/Reservations_View.class.php';
require_once 'views/Resources_View.class.php';
require_once 'views/Reservations_Detail_View.class.php';
require_once 'views/Reservations_View_List.class.php';
require_once 'views/Resources_View_List.class.php';
require_once 'views/Schedule_Form_Header_View.class.php';
// FORMS
require_once 'HTML/QuickForm2.php';
require_once 'HTML/Table.php';
require_once 'forms/Report_Form.class.php';
require_once 'forms/Schedule_Form.class.php';
require_once 'forms/Edit_Resource_Form.class.php';
require_once 'forms/Add_Resource_Form.class.php';
//Constants
//define("Options_DB_PATH", dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Options_Database' . DIRECTORY_SEPARATOR . 'cvs' . DIRECTORY_SEPARATOR);
define("Images_Path", dirname(__FILE__) . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR);
define("Images_Rel_Path", 'public/images/');

//Helper Functions
require_once 'lib/helper.php';

// APP Code starts Here
$page = new My_HTML_Page();
$page->setTitle("Welcome to Resource Management System");
$page->addStyleSheet('public/HTML_QuickForm2/quickform.css');
$page->addStyleSheet('public/css/mystyle.css');
$page->addStyleSheet('public/css/calstyle.css');



$page->addScript('public/js/jquery/js/jquery-1.3.2.min.js');
//$page->addScript('public/js/jquery/js/jquery-ui-1.7.3.custom.min.js');

$page->addScript('public/HTML_QuickForm2/js/quickform.js');
$page->addScript('public/HTML_QuickForm2/js/quickform-hierselect.js');
$page->addScript('public/js/go.js');

$page_wrappper = new Div_Container("id", "wrapper");
$page_header = new Page_Header();
$page_wrappper->addContent($page_header->toString());
$page_main_content = new Page_Main_Content();
$view_container = new Div_Container("id", "view_container");
$user_view_container = new Div_Container('id', 'user_view_container'); //container user view seperates sidebar from main content
$message = new Div_Container('class', 'message');

//setting up the request controller.
if (isset($_POST['action'])) {
    $action = $_POST['action'];
} elseif (isset($_GET['action'])) {
    $action = $_GET['action'];
} else {
    $action = 'home';
}

if ($action == 'home') {
    $side_bar = new SideBar();
    $page_main_content->addContent($side_bar->toString());
    $home_view = new Home_View();
    $user_view_container->addContent($home_view->toString());
    $page_main_content->addContent($user_view_container->toString());
} elseif ($action == 'calendar') {
    $side_bar = new SideBar();
    $page_main_content->addContent($side_bar->toString());
    if (isset($_GET['do'])) {
        $month_num = $_GET['month'];
        $year = $_GET['year'];
    } else {
        $month_num = date("n"); //current month
        $year = date("Y"); // current year 
    }
    $resource_type_id;
    if (isset($_GET['resource_type_id'])) {
        $resource_type_id = $_GET['resource_type_id'];
    } else {
        $resource_type_inventory = ResourceTypeDB::getAllResourceTypes();
        $resource_type_inventory->rewind();
        $item = $resource_type_inventory->current();
        $resource_type_id = $item->getResource_type_id();
    }

    $calendar_view = new Calendar_View($month_num, $year, $resource_type_id);
    $user_view_container->addContent($calendar_view->toString());
    $page_main_content->addContent($user_view_container->toString());
} elseif ($action == 'reports') {
    $side_bar = new SideBar();
    $page_main_content->addContent($side_bar->toString());
    $reports_view = new Reports_View();
    $user_view_container->addContent($reports_view->toString());
    $form = new Report_Form('report');
    $form = $form->getForm();
    if ($form->validate()) {//checks if form has been submitted
        $form_to_array = $form->getValue();
        $year = $form_to_array['year'];
        $week = $form_to_array['week'];
        $month = $form_to_array['month'];
        $resource_type_id = $form_to_array['resource_type_id'];
       
        $resource_utilization_str = getResourceUtilization($resource_type_id, $year, $month, $week);
        $user_view_container->addContent('<h2>Result:</h2><p>' . $resource_utilization_str . '</p>');
        
    } else {
        $user_view_container->addContent($form);
        
    }
    $page_main_content->addContent($user_view_container->toString());
} elseif ($action == 'resources') {
    $side_bar = new SideBar();
    $page_main_content->addContent($side_bar->toString());
    $resources_view = new Resources_View();
    $user_view_container->addContent($resources_view->toString());
    $page_main_content->addContent($user_view_container->toString());
} elseif ($action == 'resources_list') {
    $side_bar = new SideBar();
    $page_main_content->addContent($side_bar->toString());
    if (isset($_POST['resource_type_id'])) {
        $resource_type_id = $_POST['resource_type_id'];
    } elseif (isset($_GET['resource_type_id'])) {
        $resource_type_id = $_GET['resource_type_id'];
    } else {
        //resource_type_id not found
    }


    if (isset($_POST['resource_grp_id'])) {
        foreach ($_POST['resource_grp_id'] as $resource_id) {
            ResourceDB::deleteResource($resource_id);
        }
    }
    $resources_list_view = new Resources_View_List($resource_type_id);
    $user_view_container->addContent($resources_list_view->toString());
    $page_main_content->addContent($user_view_container->toString());
} elseif ($action == 'reservations') {
    $side_bar = new SideBar();
    $page_main_content->addContent($side_bar->toString());
    $reservations_view = new Reservations_View();
    $user_view_container->addContent($reservations_view->toString());
    $page_main_content->addContent($user_view_container->toString());
} elseif ($action == 'reservations_list') {
    $side_bar = new SideBar();
    $page_main_content->addContent($side_bar->toString());

    if (isset($_POST['resource_type_id'])) {
        $resource_type_id = $_POST['resource_type_id'];
    } elseif (isset($_GET['resource_type_id'])) {
        $resource_type_id = $_GET['resource_type_id'];
    } else {
        //resource_type_id not found
    }
    if (isset($_POST['reservation_grp_id'])) {
        foreach ($_POST['reservation_grp_id'] as $reservation_id) {
            ReservationDB::deleteReservation($reservation_id);
        }
    }

    $reservations_list_view = new Reservations_View_List($resource_type_id);
    $user_view_container->addContent($reservations_list_view->toString());
    $page_main_content->addContent($user_view_container->toString());
} elseif ($action == 'schedule') {
    $side_bar = new SideBar();
    $page_main_content->addContent($side_bar->toString());
    $day = $_REQUEST['day'];
    $year = $_REQUEST['year'];
    $month_num = $_REQUEST['month'];
    $resource_type_id = $_REQUEST['resource_type_id'];
    if (isset($day) && isset($month_num) && isset($year) && isset($resource_type_id)) {
        $today_date = date("j F Y");
        $today_timestapm = strtotime($today_date);

        $cal_date = $day . '-' . $month_num . '-' . $year;
        $cal_date = new DateTime($cal_date);
        $cal_date_timestamp = strtotime($cal_date->format("j F Y"));

        //heading
        $form_heading = new Schedule_Form_Header_View($day, $month_num, $year, $resource_type_id);
        $form = new Schedule_form('schedule', $day, $month_num, $year, $resource_type_id);
        $form = $form->getForm();
        if ($form->validate()) {
            $reservation = new Reservation();
            $user = new \User();
            $form_to_array = $form->getValue();
            $reservation->setValuesFromArray($form_to_array);
            $user->setValuesFromArray($form_to_array);
            //missing user_id and resource_id
            //check if the user already exits if not add the user to the database
            //if the user already exits the her or his data can be updated if provided.

            $user_exists = UserDB::userExists($user->getEmail());
            if ($user_exists) {
                $saved_user = UserDB::getUserByEmail($user->getEmail());
                $user->setUser_id($saved_user->getUser_id());
                UserDB::updateUser($user);
                //check if any updates
            } else {
                UserDB::insertUser($user);
            }

            $user_id = UserDB::getUserIDByEmail($user->getEmail());
            //get resource id by checking if any resource avaiable
            $resource_count = ResourceDB::getResourceCount($resource_type_id);
            $selected_slots = $form_to_array['selected_slots'];
            foreach ($selected_slots as $slot_id) {
                $reservation->setSlot_id($slot_id);
                $reservation->setUser_id($user->getUser_id());
                $reservation->setReservation_id(uniqid());
                $reserved_resources_ids = ReservationDB::getReservedResourceIDs($reservation->getSlot_date(), $reservation->getSlot_id(), $resource_type_id);
                $all_resources_ids = ResourceDB::getAllResourceIDs($resource_type_id);
                $array1 = convert2Dto1D($all_resources_ids);
                $array2 = convert2Dto1D($reserved_resources_ids);
                $array3 = array_diff($array1, $array2);
                $array3 = array_values($array3);

                if (count($array3) > 0) {
                    $reservation->setResource_id($array3[0]);
                    if (ReservationDB::insertReservation($reservation)) {
                        $message->addContent('<p class="mysuccess">Your reservation has been successfully completed. (Resource ID: ' . $reservation->getResource_id() . ', Slot ID: ' . $reservation->getSlot_id() . ')</p>');
                    } else {
                        $message->addContent('<p class="myerror">unable to make reservation. (Resource ID: ' . $reservation->getResource_id() . ', Slot ID: ' . $reservation->getSlot_id() . ') </p>');
                    }
                } else {
                    $resource_type_name = ResourceTypeDB::getResourceTypeNameByID($resource_type_id);
                    $message->addContent('<p class="myinfo">unable to make reservation. All available ' . $resource_type_name . ' are reserved.</p>');
                }
            }
            $user_view_container->addContent($message->toString());
            $page_main_content->addContent($user_view_container->toString());
        } else {
            $user_view_container->addContent($form_heading->toString());
            if ($today_timestapm <= $cal_date_timestamp) {
                $user_view_container->addContent($form);
            } else {
                $message->addContent('<p class="myinfo">You cannot make reservations on past dates!</p>');
                $user_view_container->addContent($message->toString());
            }
            $page_main_content->addContent($user_view_container->toString());
        }
    } else {
        $message->addContent('<p class="myerror">invalid page.</p>');
        $user_view_container->addContent($message->toString());
        $page_main_content->addContent($user_view_container->toString());
    }
} elseif ($action == 'edit_resource') {
    $side_bar = new SideBar();
    $page_main_content->addContent($side_bar->toString());
    if (isset($_POST['resource_id'])) {
        $resource_id = $_POST['resource_id'];
    } elseif (isset($_GET['resource_id'])) {
        $resource_id = $_GET['resource_id'];
    } else {
        
    }
    $form = new Edit_Resource_Form('edit_resource_form', $resource_id);
    $form = $form->getForm();
    if ($form->validate()) {
        $resource = new Resource();
        $form_to_array = $form->getValue();
        $resource->setValuesFromArray($form_to_array);
        $rowsAffected = ResourceDB::updateResource($resource);
        if ($rowsAffected == 1 || $rowsAffected == 0) {
            $message->addContent('<p class="mysuccess">The resource information has been successfully updated.</p>');
            $user_view_container->addContent($message->toString());
            $page_main_content->addContent($user_view_container->toString());
        } else {
            $message->addContent('<p class="myerror">unable to update the resource information.</p>');
            $user_view_container->addContent($message->toString());
            $page_main_content->addContent($user_view_container->toString());
        }
    } else {
        $user_view_container->addContent($form);
        $page_main_content->addContent($user_view_container->toString());
    }
} elseif ($action == 'add_resource') {
    $side_bar = new Sidebar();
    $page_main_content->addContent($side_bar->toString());

    if (isset($_POST['resource_type_id'])) {
        $resource_type_id = $_POST['resource_type_id'];
    } elseif (isset($_GET['resource_type_id'])) {
        $resource_type_id = $_GET['resource_type_id'];
    } else {
        //resource_type_id not found
    }

    $form = new Add_Resource_Form('add_resource_form', $resource_type_id);
    $form = $form->getForm();
    if ($form->validate()) {
        $resource = new Resource();
        $form_to_array = $form->getValue();
        $resource->setValuesFromArray($form_to_array);
        $rowsAffected = ResourceDB::insertResource($resource);
        if ($rowsAffected) {
            $message->addContent('<p class="mysuccess">The resource information has been successfully added.</p>');
            $user_view_container->addContent($message->toString());
            $page_main_content->addContent($user_view_container->toString());
        } else {
            $message->addContent('<p class="myerror">unable to add the resource.</p>');
            $user_view_container->addContent($message->toString());
            $page_main_content->addContent($user_view_container->toString());
        }
    } else {
        $heading = new Div_Container('id', 'add_resource_heading');
        $resource_type = ResourceTypeDB::getResourceTypeByID($resource_type_id);
        $heading->addContent('<h1>Add New ' . $resource_type->getResource_type_name() . '</h1></br>');
        $user_view_container->addContent($heading->toString());
        $user_view_container->addContent($form);
        $page_main_content->addContent($user_view_container->toString());
    }
} elseif ($action == 'reservation_detail') {
    $side_bar = new SideBar();
    $page_main_content->addContent($side_bar->toString());
    $reservation_id = $_GET['reservation_id'];
    $reservation_detail_view = new Reservations_Detail_View($reservation_id);
    $user_view_container->addContent($reservation_detail_view->toString());
    $page_main_content->addContent($user_view_container->toString());
} else {
    //invalid page
    $message->addContent('<p class="myerror">Invalid Page.</p>');
    $view_container->addContent($message->toString());
    $page_main_content->addContent($view_container->toString());
}


$page_wrappper->addContent($page_main_content->toString());
$page->addBodyContent($page_wrappper->toString());
$page->display();
?>
